<script lang="ts" setup>
import { ref, onMounted ,computed} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import {getShopOrdersAPI,updateOrderAPI} from '@/apis/order'
import {useUserStore} from '@/stores/user'
import MapContainer from "@/components/base/MapContainer.vue";
import {refundAPI} from '@/apis/alipay'

// 订单状态选项
const orderStatus = [
  { label: '全部', value: 'all' },
  { label: '待发货', value: 'pending' },
  { label: '待退款', value: 'waitRefund' },
  { label: '已发货', value: 'shipped' },
  { label: '已完成', value: 'completed' },
  { label: '已退款', value: 'refund' },
  { label: '已取消', value: 'cancelled' }
]

// 当前选中的状态标签
const activeTab = ref('all')

// 订单列表数据
const orderList = ref([])

// 加载订单数据
const loadOrders = async () => {
  try {
    // TODO: 调用后端API获取订单数据
    const res = await getShopOrdersAPI(useUserStore().myShop.shopId)
    orderList.value = res.data
    console.log(res.data)
  } catch (error) {
    ElMessage.error('获取订单数据失败')
  }
}

// 处理订单发货
const handleShip = async (orderId: string) => {
  try {
    await ElMessageBox.confirm('确认发货该订单？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用发货API
    await updateOrderAPI(orderId,3)
    ElMessage.success('发货成功')
    loadOrders(activeTab.value)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发货失败')
    }
  }
}

async function alipayRefund(order) {
  const data={
    out_trade_no:order.oid,
    refund_amount:order.total_amount
  }
  const res= await refundAPI(data)
  if(res.fundChange==='Y'){
    //退款成功
    orderList.value.forEach(item=>{
      if(item.oid===order.oid){
        item.status=7
      }
    })
    //后端更新订单
    await updateOrderAPI(order.oid, 7)
    //刷新数据
    await loadOrders(activeTab.value)
  }
  ElMessage({
    type:res.fundChange==='Y'?'success':'error',
    message:res.fundChange==='Y'?'已退款':'退款失败'
  })
}


function handleRefund(order:object) {
  ElMessageBox.confirm(
      '确认退款吗',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    alipayRefund(order)
    // const res= await updateOrderAPI(oid,7)
    //   ElMessage({
    //     type:res.code===200?'success':'error',
    //     message:res.code===200?'已退款':'退款失败'
    //   })
    // await loadOrders(activeTab.value)
      })
}

function getStatusText(status):string {
  switch (status) {
    case 0:return '待顾客付款'
    case 1:return '顾客取消订单'
    case 2:return '待发货'
    case 3:return '待顾客收货'
    case 4:return '已完成'
    case 5:return '顾客申请退款'
    case 6:return '已完成'
    case 7:return '已退款'
  }
}
// 标签页切换处理
const handleTabChange = (tab: TabsPaneContext) => {
  activeTab.value = tab.props.name as string
  loadOrders(activeTab.value)
}

// 计算属性用于过滤数据
const filteredOrderList = computed(() => {
  return orderList.value.filter(item => {
    switch (activeTab.value) {
      case 'all':return true
      case 'pending':return item.status===2
      case 'waitRefund':return item.status===5
      case 'shipped':return item.status===3
      case 'completed':return item.status===4
      case 'refund':return item.status===7
      case 'cancelled':return item.status===1
    }
  })
})

async function updateOrderStatus(oid,status) {
  const res=await updateOrderAPI(oid,status)
}


function formatTimestamp(timestamp) {
  const date = new Date(timestamp); // 创建日期对象
  const year = date.getFullYear(); // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份（注意月份从0开始）
  const day = String(date.getDate()).padStart(2, '0'); // 获取日期
  const hours = String(date.getHours()).padStart(2, '0'); // 获取小时
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 返回格式化后的字符串
}

onMounted(() => {
  loadOrders()
})

const mapDialogVisible=ref(false)
</script>

<template>
  <div class="panel">
    <h2 class="title">订单管理</h2>
    
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane
        v-for="status in orderStatus"
        :key="status.value"
        :label="status.label"
        :name="status.value"
      >
        <el-table class="table" :data="filteredOrderList" :default-sort="{ prop: 'status', order: 'descending' }" >
          <el-table-column prop="oid" label="订单号" width="120" align="center"/>
          <el-table-column prop="" label="下单时间" width="180" align="center">
            <template #default="scope">
              {{formatTimestamp(scope.row.created_date)}}
            </template>
            </el-table-column>
          <el-table-column prop="buyer_id" label="买家" width="120" align="center"/>
          <el-table-column prop="total_amount" label="订单金额" width="120" align="center"/>
          <el-table-column prop="order_message" label="备注" width="120" align="center"/>
          <el-table-column prop="status" label="状态" width="120"align="center">
            <template #default="scope">
              <el-tag :type="[3,4,6].includes(scope.row.status)? 'success' : 'error'">
                {{ getStatusText(scope.row.status)}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.status === 2" type="primary" size="small" @click="handleShip(scope.row.oid)">发货</el-button>
              <el-button v-if="scope.row.status === 5" type="danger" size="small" @click="handleRefund(scope.row)">退款</el-button>
              <el-button v-if="scope.row.status === 3" type="primary" size="small" @click="mapDialogVisible = true">查看物流</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="mapDialogVisible" title="物流进度" width="800">
      <MapContainer style="width: 100%;height: 400px;"></MapContainer>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.panel {
  width: 100%;
  max-width: 990px;
  min-height: 400px;
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  
  .title {
    margin: 0 0 30px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }
}

.table {
  margin-top: 20px;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header {
      background-color: #f8f9fa;
    }
    
    .el-table__row {
      &:hover {
        background-color: #f0f7ff;
      }
    }
  }
}

:deep(.el-tabs) {
  .el-tabs__header {
    margin-bottom: 30px;
  }
  
  .el-tabs__nav-wrap {
    &::after {
      background-color: #e9ecef;
    }
  }
  
  .el-tabs__item {
    font-size: 14px;
    padding: 0 20px;
    
    &.is-active {
      color: #007bff;
      font-weight: 600;
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    background-color: #f8f9fa;
    padding: 20px 30px;
    border-bottom: 1px solid #e9ecef;
  }
  
  .el-dialog__body {
    padding: 30px;
  }
}
</style>